package cn.cena.org.controller;

import cn.cena.basic.util.AjaxResult;
import cn.cena.basic.util.PageList;
import cn.cena.org.domian.Department;
import cn.cena.org.query.DepartmentQuery;
import cn.cena.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询一条
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation(value = "查询一条数据",notes = "传入一个id")
    public Department loadOne(@PathVariable("id")Long id){
        return departmentService.loadOne(id);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有",notes = "不需要参数")
    public List<Department> loadAll(){
        return departmentService.loadAll();
    }

    /**
     *  高级查询
     * @param query
     * @return
     */
    @PostMapping
    @ApiOperation(value = "分页查询",notes = "分页")
    public PageList<Department> loadByQuery(@RequestBody DepartmentQuery query){
        return departmentService.queryData(query);
    }

        @DeleteMapping("{id}")
    @ApiOperation(value = "根据id删除",notes = "传入一个id")
    public AjaxResult del(@PathVariable Long id){
        try {
            departmentService.remove(id);
            return AjaxResult.result();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.result().setMsg("删除失败");
        }
    }
    @PatchMapping
    @ApiOperation(value = "根据id批量删除",notes = "传入多个id")
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            departmentService.patchRemove(ids);
            return AjaxResult.result();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.result().setMsg("删除失败");
        }
    }

    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addAndUpdate(@RequestBody Department department){
        try {
            if (department.getId()==null){
                departmentService.add(department);
            } else {
                departmentService.update(department);
            }
            return AjaxResult.result();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.result().setMsg("操作失败");
        }
    }

    @GetMapping("/tree")
    @ApiOperation(value = "查询部门树",notes = "不需要参数")
    public List<Department> parentTree(){
        return departmentService.parentTree();
    }
}
